package com.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.pojo.Course;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SetCourseActivity extends AppCompatActivity {

    private ImageButton 后退按钮;
    private TextView 标题;
    private TextView 副标题;
    private ListView 列表;

    private List<Map<String,String>> data = new ArrayList<>();//所有记录
    private SimpleAdapter listAdapter; //适配器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_course);

        后退按钮 = (ImageButton) findViewById(R.id.后退按钮);
        标题 = (TextView) findViewById(R.id.标题);
        副标题 = (TextView) findViewById(R.id.副标题);
        列表 = (ListView) findViewById(R.id.列表);


        后退按钮.setColorFilter(Color.BLACK);

        后退按钮.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                SetCourseActivity.this.finish();
                Intent intent = new Intent();
                intent.setClass(SetCourseActivity.this,AdminActivity.class);
                startActivity(intent);
            }
        });

        标题.setText("课程管理");
        标题.setTextColor(Color.BLACK);

        副标题.setText("新增课程");
        副标题.setTextColor(Color.parseColor("#5599FF"));

        副标题.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                SetCourseActivity.this.finish();
                Intent intent = new Intent();
                intent.setClass(SetCourseActivity.this,AddCourseActivity.class);
                startActivity(intent);
            }
        });

        String path1 = "http://101.200.40.47:8080/stu/course/getCourseList";
        new getCourseList().execute(path1);
    }

    //获得课程列表
    private class getCourseList extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET  
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();

            JSONArray jsonArray = null;

            try {
                jsonArray = new JSONArray(info);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Map<String, String> hashMap = new HashMap<>();
                    hashMap.put("cid", jsonObject.getString("cid"));
                    hashMap.put("courseName", jsonObject.getString("courseName"));
                    hashMap.put("courseTeacher", "任课老师："+jsonObject.getString("courseTeacher"));
                    hashMap.put("courseNumber","已选人数："+jsonObject.getString("courseNumber"));
                    hashMap.put("startDate", "开课时间："+jsonObject.getString("startDate"));
                    hashMap.put("endDate", "结课时间："+jsonObject.getString("endDate"));
                    data.add(hashMap);
                    showList();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //新建适配器
    private class MyAdapter extends SimpleAdapter {
        //上下文
        Context context ;
        public MyAdapter(Context context,
                         List<? extends Map<String, ?>> data, int resource, String[] from,
                         int[] to) {
            super(context, data, resource, from, to);
            this.context = context;
        }
        @Override
        public View getView(final int i, final View convertView, ViewGroup viewGroup) {
            View view = super.getView(i, convertView, viewGroup);
            final Button btn1 = (Button) view.findViewById(R.id.编辑按钮);
            final Button btn2 = (Button) view.findViewById(R.id.删除按钮);
            btn1.setTag(i);//设置标签
            btn2.setTag(i);//设置标签
            btn1.setOnClickListener(new android.view.View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    Map<String, String> map = data.get((int) v.getTag());
                    Course course = new Course();
                    course.setCid(map.get("cid"));
                    course.setCourseName(map.get("courseName"));
                    course.setCourseTeacher(map.get("courseTeacher").substring(5));
                    course.setStartDate(map.get("startDate").substring(5));
                    course.setEndDate(map.get("endDate").substring(5));
                    SetCourseActivity.this.finish();
                    Intent intent = new Intent();
                    intent.putExtra("course",course);
                    intent.setClass(SetCourseActivity.this,EditCourseActivity.class);
                    startActivity(intent);

                }
            });

            btn2.setOnClickListener(new android.view.View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    Map<String, String> map = data.get((int) v.getTag());
                    String cid = map.get("cid");
                    String path3 = "http://101.200.40.47:8080/stu/course/delCourse?cid="+cid;
                    new DelCourse().execute(path3);
                    SetCourseActivity.this.finish();
                    Intent intent = new Intent();
                    intent.setClass(SetCourseActivity.this,SetCourseActivity.class);
                    startActivity(intent);

                }
            });
            return view;
        }
    }

    //删除课程
    private class  DelCourse extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET  
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            if(info.equals("1")){
                Toast.makeText(SetCourseActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
            }else if((info.equals("0"))){
                Toast.makeText(SetCourseActivity.this, "删除失败！", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(SetCourseActivity.this, "未知错误！删除失败！", Toast.LENGTH_SHORT).show();
            }
        }
    }


    //显示所有的记录
    public void showList(){
        listAdapter = new MyAdapter(this,data,
                R.layout.setlist,
                new String[]{"courseName","courseTeacher","startDate","endDate","courseNumber"},
                new int[]{R.id.课程名称,R.id.任课老师,R.id.开课时间,R.id.结课时间,R.id.选课人数});
        列表.setAdapter(listAdapter);

    }

    long mExitTime;       //实现“再按一次退出”的记录时间变量
    @Override //再按一次退出程序
    public void onBackPressed() {
        if (System.currentTimeMillis() - mExitTime < 2000) {
            super.onBackPressed();
        } else {
            mExitTime = System.currentTimeMillis();
            Toast.makeText(SetCourseActivity.this,"再按一次退出应用",Toast.LENGTH_SHORT).show();
        }
    }
}
